<template>
  <Page
    title="流程实例管理"
    description="查看和管理流程实例，支持查看流程追踪、变量管理"
  >
    <div class="flex h-full flex-col">
      <!-- 查询表单 -->
      <div class="mb-4 rounded-lg bg-white p-4">
        <Form layout="inline" :model="queryParams">
          <FormItem label="流程名称">
            <Input
              v-model:value="queryParams.processDefinitionName"
              placeholder="请输入流程名称"
              allow-clear
              style="width: 200px"
            />
          </FormItem>
          <FormItem label="发起人">
            <Input
              v-model:value="queryParams.startUserId"
              placeholder="请输入发起人"
              allow-clear
              style="width: 150px"
            />
          </FormItem>
          <FormItem label="状态">
            <Select
              v-model:value="queryParams.state"
              placeholder="请选择状态"
              allow-clear
              style="width: 120px"
            >
              <SelectOption value="ACTIVE">运行中</SelectOption>
              <SelectOption value="SUSPENDED">已挂起</SelectOption>
              <SelectOption value="COMPLETED">已完成</SelectOption>
            </Select>
          </FormItem>
          <FormItem>
            <Space>
              <Button type="primary" @click="handleQuery">
                <template #icon><SearchOutlined /></template>
                查询
              </Button>
              <Button @click="handleReset">
                <template #icon><ReloadOutlined /></template>
                重置
              </Button>
            </Space>
          </FormItem>
        </Form>
      </div>

      <!-- 数据表格 -->
      <div class="flex-1 overflow-hidden">
        <Grid class="h-full" @page-change="handlePageChange">
          <!-- 状态列 -->
          <template #state="{ row }">
            <Tag v-if="!row.ended && !row.suspended" color="processing">
              运行中
            </Tag>
            <Tag v-else-if="row.suspended" color="warning"> 已挂起 </Tag>
            <Tag v-else-if="row.ended" color="success"> 已完成 </Tag>
          </template>

          <!-- 耗时列 -->
          <template #duration="{ row }">
            <span v-if="row.durationInMillis">
              {{ formatDuration(row.durationInMillis) }}
            </span>
            <span v-else style="color: #999">-</span>
          </template>

          <!-- 操作列 -->
          <template #action="{ row }">
            <Space>
              <Button
                v-permission="'workflow:instance:view'"
                type="link"
                size="small"
                @click="handleViewDetail(row)"
              >
                详情
              </Button>
              <Button
                v-permission="'workflow:instance:track'"
                type="link"
                size="small"
                @click="handleViewDiagram(row)"
              >
                流程追踪
              </Button>
              <Button
                v-if="!row.ended && !row.suspended"
                v-permission="'workflow:instance:suspend'"
                type="link"
                size="small"
                @click="handleSuspend(row)"
              >
                挂起
              </Button>
              <Button
                v-if="row.suspended"
                v-permission="'workflow:instance:activate'"
                type="link"
                size="small"
                @click="handleActivate(row)"
              >
                激活
              </Button>
              <Button
                v-permission="'workflow:instance:delete'"
                type="link"
                size="small"
                danger
                @click="handleDelete(row)"
              >
                删除
              </Button>
            </Space>
          </template>
        </Grid>
      </div>
    </div>

    <!-- 流程追踪弹窗 -->
    <Modal
      v-model:open="diagramVisible"
      width="90%"
      :footer="null"
      :closable="true"
      :destroy-on-close="true"
      wrap-class-name="workflow-diagram-modal"
      @cancel="handleCloseDiagram"
    >
      <template #title>
        <div class="diagram-modal-title">
          <span class="title-text">流程追踪</span>
          <div class="title-info">
            <Tag color="blue">{{ currentInstance?.processDefinitionName }}</Tag>
            <Tag>版本 v{{ currentInstance?.processDefinitionVersion }}</Tag>
            <Tag v-if="!currentInstance?.ended && !currentInstance?.suspended" color="processing">
              运行中
            </Tag>
            <Tag v-else-if="currentInstance?.suspended" color="warning">
              已挂起
            </Tag>
            <Tag v-else-if="currentInstance?.ended" color="success">
              已完成
            </Tag>
          </div>
        </div>
      </template>

      <div class="diagram-viewer-container">
        <!-- 加载状态 -->
        <div v-if="diagramLoading" class="loading-wrapper">
          <Spin size="large" tip="正在加载流程图..." />
        </div>
        <!-- BPMN 查看器 -->
        <BpmnViewer
          v-else-if="currentBpmnXml"
          :key="currentInstance?.id"
          :bpmn-xml="currentBpmnXml"
          :highlighted-nodes="currentActiveNodes"
          :finished-nodes="currentFinishedNodes"
        />
        <!-- 空状态 -->
        <div v-else class="empty-diagram">
          <div class="empty-icon">📊</div>
          <div class="empty-text">暂无流程图</div>
        </div>
      </div>
    </Modal>
  </Page>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import { Page } from '@vben/common-ui';

import {
  Button,
  Form,
  FormItem,
  Input,
  Modal,
  Select,
  SelectOption,
  Space,
  Spin,
  Tag,
  message,
} from 'ant-design-vue';
import { ReloadOutlined, SearchOutlined } from '@ant-design/icons-vue';
import { useVbenVxeGrid } from '@vben/plugins/vxe-table';

import type { ProcessInstance } from '#/api/workflow';
import {
  activateProcessInstanceApi,
  deleteProcessInstanceApi,
  getProcessInstanceDiagramApi,
  getProcessInstanceListApi,
  suspendProcessInstanceApi,
} from '#/api/workflow';

import BpmnViewer from '../components/bpmn-viewer/index.vue';

const router = useRouter();

// 查询参数
const queryParams = reactive({
  processDefinitionName: undefined,
  startUserId: undefined,
  state: undefined,
  pageNum: 1,
  pageSize: 10,
});

// 流程追踪相关
const diagramVisible = ref(false);
const diagramLoading = ref(false);
const currentBpmnXml = ref('');
const currentInstance = ref<ProcessInstance>();
const currentActiveNodes = ref<string[]>([]);
const currentFinishedNodes = ref<string[]>([]);

// 表格配置
const [Grid, gridApi] = useVbenVxeGrid<ProcessInstance>({
  gridOptions: {
    data: [],
    loading: false,
    pagerConfig: {
      enabled: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      pageSizes: [10, 20, 50, 100],
      layouts: [
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'Total',
      ],
    },
    columns: [
      {
        field: 'processDefinitionName',
        title: '流程名称',
        minWidth: 200,
      },
      {
        field: 'processDefinitionVersion',
        title: '版本',
        width: 80,
      },
      {
        field: 'businessKey',
        title: '业务键',
        minWidth: 120,
      },
      {
        field: 'startUserName',
        title: '发起人',
        width: 120,
      },
      {
        field: 'state',
        title: '状态',
        width: 100,
        slots: { default: 'state' },
      },
      {
        field: 'startTime',
        title: '开始时间',
        minWidth: 165,
      },
      {
        field: 'endTime',
        title: '结束时间',
        minWidth: 165,
      },
      {
        field: 'durationInMillis',
        title: '耗时',
        width: 120,
        slots: { default: 'duration' },
      },
      {
        field: 'action',
        title: '操作',
        width: 300,
        align: 'center',
        fixed: 'right',
        slots: { default: 'action' },
      },
    ],
  },
});

// 查询列表
async function fetchList() {
  gridApi.setState({ gridOptions: { loading: true } });
  try {
    const data = await getProcessInstanceListApi(queryParams);
    gridApi.setState({
      gridOptions: {
        data: data.list,
        loading: false,
        pagerConfig: {
          currentPage: data.pageNum,
          pageSize: data.pageSize,
          total: data.total,
        },
      },
    });
  } catch (error: any) {
    message.error(error?.msg || '查询失败');
    gridApi.setState({ gridOptions: { loading: false } });
  }
}

// 分页变化
function handlePageChange({ currentPage, pageSize }: any) {
  queryParams.pageNum = currentPage;
  queryParams.pageSize = pageSize;
  fetchList();
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1;
  fetchList();
}

// 重置
function handleReset() {
  queryParams.processDefinitionName = undefined;
  queryParams.startUserId = undefined;
  queryParams.state = undefined;
  queryParams.pageNum = 1;
  fetchList();
}

// 格式化耗时
function formatDuration(milliseconds: number): string {
  if (!milliseconds) return '-';

  const seconds = Math.floor(milliseconds / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);

  if (days > 0) {
    return `${days}天${hours % 24}小时`;
  }
  if (hours > 0) {
    return `${hours}小时${minutes % 60}分钟`;
  }
  if (minutes > 0) {
    return `${minutes}分钟${seconds % 60}秒`;
  }
  return `${seconds}秒`;
}

// 查看详情
function handleViewDetail(record: ProcessInstance) {
  router.push(`/workflow/instance/detail/${record.id}`);
}

// 查看流程图（流程追踪）
async function handleViewDiagram(record: ProcessInstance) {
  currentInstance.value = record;
  diagramVisible.value = true;
  diagramLoading.value = true;

  try {
    const data = await getProcessInstanceDiagramApi(record.id!);
    currentBpmnXml.value = data.bpmnXml;
    currentActiveNodes.value = data.activeActivityIds || [];
    currentFinishedNodes.value = data.finishedActivityIds || [];
  } catch (error: any) {
    message.error(error?.msg || '加载流程图失败');
    currentBpmnXml.value = '';
  } finally {
    diagramLoading.value = false;
  }
}

// 关闭流程图弹窗
function handleCloseDiagram() {
  diagramVisible.value = false;
  currentBpmnXml.value = '';
  currentInstance.value = undefined;
  currentActiveNodes.value = [];
  currentFinishedNodes.value = [];
}

// 挂起
async function handleSuspend(record: ProcessInstance) {
  try {
    await suspendProcessInstanceApi(record.id!);
    message.success('挂起成功');
    await fetchList();
  } catch (error: any) {
    message.error(error?.msg || '挂起失败');
  }
}

// 激活
async function handleActivate(record: ProcessInstance) {
  try {
    await activateProcessInstanceApi(record.id!);
    message.success('激活成功');
    await fetchList();
  } catch (error: any) {
    message.error(error?.msg || '激活失败');
  }
}

// 删除
function handleDelete(record: ProcessInstance) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除该流程实例吗？`,
    onOk: async () => {
      try {
        await deleteProcessInstanceApi(record.id!);
        message.success('删除成功');
        await fetchList();
      } catch (error: any) {
        message.error(error?.msg || '删除失败');
      }
    },
  });
}

// 初始化加载数据
onMounted(() => {
  fetchList();
});
</script>

<style scoped>
/* 弹窗标题样式 */
.diagram-modal-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.title-text {
  font-size: 16px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.88);
}

.title-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 查看器容器 */
.diagram-viewer-container {
  height: 75vh;
  min-height: 600px;
  max-height: 800px;
  width: 100%;
  background: #fafafa;
  border-radius: 4px;
}

.diagram-viewer-container :deep(.bpmn-viewer) {
  height: 100%;
  width: 100%;
}

/* 加载状态 */
.loading-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: #fff;
  border-radius: 4px;
}

/* 空状态 */
.empty-diagram {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: #fff;
  border-radius: 4px;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  opacity: 0.3;
}

.empty-text {
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
}
</style>

<style>
/* 流程图弹窗全局样式 */
.workflow-diagram-modal .ant-modal-content {
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  overflow: hidden;
}

.workflow-diagram-modal .ant-modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.workflow-diagram-modal .ant-modal-body {
  flex: 1;
  padding: 16px;
  overflow: hidden;
  background: #fafafa;
}

/* 关闭按钮样式优化 */
.workflow-diagram-modal .ant-modal-close {
  opacity: 1 !important;
}

.workflow-diagram-modal .ant-modal-close-x {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}

/* 隐藏可能的重复元素 */
.workflow-diagram-modal .ant-modal-close-x > * + * {
  display: none !important;
}
</style>

